/**
 * 
 */
package edu.cmu.cs211.seamcarving;

/**
 * A filter object that calculate the magnitude of the gradient of a GrayImage.
 * 
 * The magnitude of the gradient at a point is defined as:
 * 
 * g(i,j) = sqrt( ( p(i,j+1)-p(i,j) ) ^2 + ( p(i+1,j)-p(i,j) ) ^2 )
 * 
 * where p(i,j) is the value of the pixel at (i,j)
 * 
 * Any point outside of the frame is considered to have a pixel value 0
 *
 */
public class GradientFilter {
  
  public GradientFilter() {
    
  }
  
  /**
   * Apply filter to the image
   * 
   * @param image Image to filter
   * @return A resulting image of the gradient magnitude
   */
  public GrayImage filter(GrayImage image) {
	  int rows = image.getHeight();	//height
	  int cols = image.getWidth();	//width
	  float[][] result = new float[rows][cols];	//result array
	  float vali;	//(i+1, j)
	  float valj;	//(i, j+1)
	  
	  // loop through the array, and calculate the magnitude of the gradient
	  for(int i = 0; i < rows; i++)
	  {
		  for(int j = 0; j < cols; j++)
		  {
			  float val = image.get(i, j);
			  if(i == rows-1)	//if i is the last element in the col, set i value to 0
				  vali = 0;
			  else
				  vali = image.get(i+1, j);
			  if(j == cols-1)	//if j is the last element in the row, set j value to 0
				  valj = 0;
			  else
				  valj = image.get(i, j+1);
			  
			  result[i][j] = (float) Math.sqrt(Math.pow((valj-val), 2) + Math.pow((vali-val), 2));
		  }
	  }
	  return new GrayImage(result);
  }
}
